package com.oceansoft.core.message;

import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;

import org.codehaus.jackson.map.ObjectMapper;

public class JsonUtil {

	/** 空的 {@code JSON} 数据 - <code>"{}"</code>。 */
	public static final String EMPTY_JSON = "{}";

	/** 空的 {@code JSON} 数组(集合)数据 - {@code "[]"}。 */
	public static final String EMPTY_JSON_ARRAY = "[]";

	private static ObjectMapper mapper = new ObjectMapper();

	public static String toJson(Object target) {
		String result = EMPTY_JSON;
		try {
			result = mapper.writeValueAsString(target);
		} catch (Exception ex) {
			if (target instanceof Collection<?>
					|| target instanceof Iterator<?>
					|| target instanceof Enumeration<?>
					|| target.getClass().isArray()) {
				result = EMPTY_JSON_ARRAY;
			}
		}
		return result;
	}

	public static <T> T fromJson(String json, Class<T> clazz) {
		if (json == null || "".equals(json.trim())) {
			return null;
		}
		try {
			return (T) mapper.convertValue(json, clazz);
		} catch (Exception ex) {
			return null;
		}

	}

	@SuppressWarnings("unchecked")
	public static Map<String, Object> fromJsonToMap(String json) {
		if (json == null || "".equals(json.trim())) {
			return null;
		}
		try {
			return mapper.readValue(json, Map.class);
		} catch (Exception ex) {
			return null;
		}

	}

	public static void main(String[] args) {
	}
}
